﻿using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace GameToolkit
{
    public class MyEventSystem : EventSystem
    {
        public static Selectable CurrentSelectable
        {
            get
            {
                if (current is MyEventSystem mysys)
                    return mysys.mSelected;
                else
                    return null;
            }
        }

        public event System.Action<Selectable> OnSelectionChanged;
        public Selectable currentSelectable => mSelected;

        GameObject mSelectedObj;
        Selectable mSelected;

        protected override void Update()
        {
            base.Update();
            var sel = currentSelectedGameObject;
            if (mSelectedObj != sel)
            {
                mSelectedObj = sel;
                Selectable selected;
                if (sel == null || !sel.TryGetComponent(out selected))
                    selected = null;
                if (selected != mSelected)
                {
                    mSelected = selected;
                    OnSelectionChanged?.Invoke(selected);
                }
            }
        }

        protected override void OnDisable()
        {
            base.OnDisable();
            mSelected = null;
            mSelectedObj = null;
            OnSelectionChanged = null;
        }

    }
}
